<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <link rel="stylesheet" type="text/css" href="mystyle.css"/>
  <!--Load the AJAX API-->
<!--
  <script type="text/javascript" src="http://www.google.com/jsapi"></script>
  <script type="text/javascript">
    // Load the Visualization API and the piechart package.
    google.load('visualization', '1', {'packages':['table']});
    google.setOnLoadCallback(drawTable);

    function drawTable() {
      var data = new google.visualization.DataTable(
      {
        cols:
        [
          {id: 'ID', label: 'ID', type: 'number'},
          {id: 'NAME', label: 'Name', type: 'string'},
          {id: 'STATUS', label: 'Status', type: 'string'},
          {id: 'RATING', label: 'Rating', type: 'number'},
          {id: 'STARTDATE', label: 'Start Date', type: 'date'},
          {id: 'DELINQUENCYRATE', label: 'Delinquency Rate', type: 'number'},
          {id: 'DEFAULTRATE', label: 'Default Rate', type: 'number'},
          {id: 'TOTALRAISED', label: 'Total Raised', type: 'number'},
          {id: '#LOANS', label: '# Loans', type: 'number'},
          {id: 'COUNRTRIES', label: 'Countries', type: 'string'}
        ],
        rows:
        [
/*
  {c:[{v:129},{v:'Tanaoba Lais Manekat Foundation (TLM)'},{v:'pilot'},{v:2.5},{v:new Date(2009,03,12)},{v:0},{v:0},{v:9850},{v:4},{v:'Indonesia'}]}
,{c:[{v:128},{v:'Hagdan sa Pag-uswag Foundation, Inc. (HSPFI)'},{v:'pilot'},{v:2},{v:new Date(2009,02,17)},{v:0},{v:0},{v:25650},{v:112},{v:'Philippines'}]}
,{c:[{v:127},{v:'EDESA'},{v:'pilot'},{v:2.5},{v:new Date(2009,02,10)},{v:0},{v:0},{v:10575},{v:11},{v:'Costa Rica'}]}
*/

        ]
      });

      var table = new google.visualization.Table(document.getElementById('partner'));

      var formatter = new google.visualization.TableNumberFormat({suffix: '%', fractionDigits: 2});
      formatter.format(data, 5);
      formatter = new google.visualization.TableNumberFormat({suffix: '%', fractionDigits: 2});
      formatter.format(data, 6);
      formatter = new google.visualization.TableNumberFormat({prefix: '$', fractionDigits: 0});
      formatter.format(data, 7);
      formatter = new google.visualization.TableNumberFormat({fractionDigits: 0});
      formatter.format(data, 8);

      //important: set allowHtml to true!
      table.draw(data, {allowHtml: true, showRowNumber: true});
    }

  </script>
-->
  <script type="text/javascript" src="jquery.js"></script>
  <script type="text/javascript" src="menu.js"></script>
  <script type="text/javascript">
    $(document).ready(function() { buildMenus(); });
  </script>
  <script type="text/javascript">var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));</script>
  <script type="text/javascript">try {var pageTracker = _gat._getTracker("UA-7674244-2");pageTracker._trackPageview();} catch(err) {}</script>
</head>
<body>





<div id="content">
  New loans.  (WORK IN PROGRESS)

  <?php
    $loanIDs = array();
    $partners = array();
  
    ///////////////////////////////////////////////////////////////////////////
    function getFile($fileName)
    {
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $fileName);
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //don't display information on page
      $file = curl_exec($ch);
      return $file;
    }

    ///////////////////////////////////////////////////////////////////////////
    //Get the Loan IDs from the newest page, which only contains a small amount of loan information
    function setLoanIDs($loansDOM)
    {
      $loans = $loansDOM->getElementsByTagname('loan');
      foreach ($loans as $loan)
      {
        //There may be multiple nodes with ID, but the loan ID will be the first one
        $nodes = $loan->getElementsByTagname('id'); $node = $nodes->item(0); $id = $node->nodeValue;
        global $loanIDs;
        $loanIDs[count($loanIDs)] = $id;
      }
    }

    //TODO: Cache this page?
    ///////////////////////////////////////////////////////////////////////////
    function setPartners()
    {
      $partnersFile = fopen("partners.xml", "r");
      $partnersDOM = new DOMDocument();

//$theData = fread($fh, filesize($myFile));
//fclose($fh);



      //$partnersDOM->loadXML();
      //fclose($partnersFile);
      //TODO: close file
    }


    ///////////////////////////////////////////////////////////////////////////
    //Parse the full loan information
    function parseLoans($loansXML)
    {
      $loansDOM = new DOMDocument();
      $loansDOM->loadXML($loansXML);
      $loans = $loansDOM->getElementsByTagname('loan');


      foreach ($loans as $loan)
      {
        echo "  <tr>\n";
        //There may be multiple nodes with ID, but the loan ID will be the first one
        $nodes = $loan->getElementsByTagname('id'); $node = $nodes->item(0); $id = $node->nodeValue;
        $nodes = $loan->getElementsByTagname('name'); $node = $nodes->item(0); $name = $node->nodeValue;
        $nodes = $loan->getElementsByTagname('status'); $node = $nodes->item(0); $status = $node->nodeValue;
        $nodes = $loan->getElementsByTagname('funded_amount'); $node = $nodes->item(0); $funded_amount = $node->nodeValue;
        $nodes = $loan->getElementsByTagname('basket_amount'); $node = $nodes->item(0); $basket_amount = $node->nodeValue;
        $nodes = $loan->getElementsByTagname('activity'); $node = $nodes->item(0); $activity = $node->nodeValue;
        $nodes = $loan->getElementsByTagname('sector'); $node = $nodes->item(0); $sector = $node->nodeValue;
        $nodes = $loan->getElementsByTagname('use'); $node = $nodes->item(0); $use = $node->nodeValue;
        $nodes = $loan->getElementsByTagname('country'); $node = $nodes->item(0); $country = $node->nodeValue;
        $nodes = $loan->getElementsByTagname('town'); $node = $nodes->item(0); $town = $node->nodeValue;

        /*
        echo "id = $id<br>";
        echo "name = $name<br>";
        echo "status = $status<br>";
        echo "funded_amount = $funded_amount<br>";
        echo "basket_amount = $basket_amount<br>";
        echo "activity = $activity<br>";
        echo "sector = $sector<br>";
        echo "use = $use<br>";
        echo "country = $country<br>";
        echo "town = $town<br>";
        */


        echo "    ".
          "<td>$id</td>".
          "<td>$name</td>".
          "<td>$status</td>".
          "<td>$funded_amount</td>".
          "<td>$basket_amount</td>".
          "<td>$activity</td>".
          "<td>$sector</td>".
          "<td>$use</td>".
          "<td>$country</td>".
          "<td>$town</td>"
        ;


        echo "\n  </tr>\n";
      }
    }



    ///////////////////////////////////////////////////////////////////////////
    //MAIN SECTION
    ///////////////////////////////////////////////////////////////////////////

    //Get the first loan file separately to get the number of pages
    $xml = getFile('http://api.kivaws.org/v1/loans/newest.xml?page=1');
    $loansDOM = new DOMDocument();
    $loansDOM->loadXML($xml);
    
    //While we've got the first page, load the Loan IDs
    setLoanIDs($loansDOM);
    
    //Find the number of pages
    $nodes = $loansDOM->getElementsByTagname('pages'); $node = $nodes->item(0); $numberOfPages = $node->nodeValue;

    //Get the rest of the pages, load all the Loan IDs
    /* TODO: Very slow, too many results
    for($pageNumber = 2; $pageNumber <= $numberOfPages; $pageNumber++)
    {
      $xml = getFile("http://api.kivaws.org/v1/loans/newest.xml?page=$pageNumber");
      $loansDOM = new DOMDocument();
      $loansDOM->loadXML($xml);
      setLoanIDs($loansDOM);
    }
    */
    
    setPartners();

    echo "<table border='1'>\n";
    //echo " <tr bgcolor='COCOCO'><th colspan='999' align='left'>Summary Metrics per Country</th></tr>\n";
    echo " <tr bgcolor='COCOCO'><th>id</th><th>name</th><th>status</th><th>funded_amount</th><th>basket_amount</th><th>activity</th><th>sector</th><th>use</th><th>country</th><th>town</th></tr>\n";





    //Get the loan information
    for($loanIndex = 0; $loanIndex < count($loanIDs); $loanIndex++)
    {
      //Get groups of 10 loans at a time (that's the most that can be retrieved at once, it's much faster to group them)
      if($loanIndex % 10 == 0)
      {
        //Concatenate the ids into a comma-separated string
        $idList = "";
        for($nextLoanIndex = $loanIndex; ($nextLoanIndex < $loanIndex+10) && ($nextLoanIndex <= count($loanIDs)-1); $nextLoanIndex++)
        {
          $idList = $idList.",".$loanIDs[$nextLoanIndex];
        }
        //Remove the first comma
        $idList = substr($idList, 1);
        
        //Now get the file
        $loansXML = getFile("http://api.kivaws.org/v1/loans/$idList.xml");
        parseLoans($loansXML);
      }
    }



    echo "</table>\n";





    /*
    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL, 'http://api.kivaws.org/v1/partners.xml');
    curl_setopt($ch, CURLOPT_HEADER, 0); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //don't display information on page
    $xml = curl_exec($ch); 
    $dom = new DOMDocument();
    $dom->loadXML($xml); 
    $partners = $dom->getElementsByTagname('partner');
  
    $partnerIndex = 1;
    foreach ($partners as $partner)
    {
      $nodes = $partner->getElementsByTagname('id'); $node = $nodes->item(0); $id = $node->nodeValue;
      $nodes = $partner->getElementsByTagname('name'); $node = $nodes->item(0); $name = $node->nodeValue;
      //Escape apostrophes
      $name = str_replace("'", "\'", $name);
      $nodes = $partner->getElementsByTagname('status'); $node = $nodes->item(0); $status = $node->nodeValue;
      $nodes = $partner->getElementsByTagname('rating'); $node = $nodes->item(0); $rating = $node->nodeValue;
      $nodes = $partner->getElementsByTagname('start_date'); $node = $nodes->item(0); $start_date = $node->nodeValue;
      //Convert this format: 2006-02-15T18:00:00Z to this: new Date(2008, 1, 28, 0, 31, 26)
      $start_date = "new Date(".substr($start_date,0,4).",".substr($start_date,5,2).",".substr($start_date,8,2).")";
      $nodes = $partner->getElementsByTagname('delinquency_rate'); $node = $nodes->item(0); $delinquency_rate = $node->nodeValue;
      $nodes = $partner->getElementsByTagname('default_rate'); $node = $nodes->item(0); $default_rate = $node->nodeValue;
      $nodes = $partner->getElementsByTagname('total_amount_raised'); $node = $nodes->item(0); $total_amount_raised = $node->nodeValue;
      $nodes = $partner->getElementsByTagname('loans_posted'); $node = $nodes->item(0); $loans_posted = $node->nodeValue;

      //TODO: Countries
      $countryNames = "";
      $countries = $partner->getElementsByTagName('country');
      foreach ($countries as $country)
      {
        $nodes = $country->getElementsByTagname('name'); $node = $nodes->item(0); $countryNames = $countryNames.",".$node->nodeValue;
        //Escape apostrophes
        $countryNames = str_replace("'", "\'", $countryNames);
      }
      $countryNames = substr($countryNames, 1); //remove first comma


      //Put comma in front, except for first item
      if($partnerIndex > 1)
      {
        echo ",";
      }
      $partnerIndex = $partnerIndex+1;

  
      echo "{c:[{v:$id},{v:'$name'},{v:'$status'},{v:$rating},{v:$start_date},";
      echo "{v:$delinquency_rate},{v:$default_rate},{v:$total_amount_raised},{v:$loans_posted},{v:'$countryNames'}]}\n";
    }
      */
  ?>





  <div id="partner"></div>
</div>
<div id="menu"></div>

</body>
</html>
